package com.template.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.template.dto.User;
import com.template.result.Result;
import com.template.service.UserService;
import com.template.utils.AliOssUtil;
import com.template.excel.ExcelImportUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.UUID;

import static com.template.excel.ExcelImportUtils.MultipartFileToFile;


@RestController
@Slf4j
@RequestMapping("/file")
public class FileController {
    @Autowired
    private UserService userService;

    @Autowired
    private AliOssUtil aliOssUtil;
    //上传到本地
//    @PostMapping("/upload")
//    public Result uploadAvatar(MultipartFile file) throws IOException {
//        log.info("新增:{}",file);
//        if (file.isEmpty()) {
//            return Result.error("图片为空");
//        }
//        String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
//////        有问题待解决
//        String fileName = new Date().getTime()+"."+fileExt;
//        ApplicationHome applicationHome = new ApplicationHome(this.getClass());
////        File files = new File(applicationHome.getDir()+"\\static\\upload\\");
//        File files=new File(System.getProperty("user.dir")+"\\src\\upload\\");
//        if(!files.exists())//路劲不存在就创建文件夹
//            files.mkdir();
////        图片地址target/classes/static/upload
////        Path uploadPath = Paths.get(applicationHome.getDir()+"\\static\\upload\\"+fileName);
//        Path uploadPath=Paths.get(System.getProperty("user.dir")+"\\src\\upload");
//        Files.copy(file.getInputStream(),uploadPath);
//
//        return Result.success(uploadPath);
////        return Result.success("http://localhost:8024/upload/"+fileName);
//    }


//上传到阿里云oss
    @PostMapping("/upload")
    public Result uploadAvatar(@RequestBody MultipartFile file) throws IOException{
        try {
            String originalFilename=file.getOriginalFilename();
            String extension=originalFilename.substring((originalFilename.lastIndexOf(".")));
            String timeId= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));
            String objectName= timeId+UUID.randomUUID().toString()+extension;
            String uploadPath = aliOssUtil.upload(file);
        System.out.println("上传的文件"+file);
//        String uploadPath="ssss";
            return Result.success(uploadPath);
        }catch (IOException e){
            log.error("文件上传失败{}",e);
        }
        return null;
    }

    @PostMapping("/importExcel")
    public Result importExcel(@RequestParam("file") MultipartFile file){
        File fileExcel = MultipartFileToFile(file);
        if (fileExcel == null) {
            return Result.error("请上传正确格式文件！");
        }
        try {
            ExcelReader reader = ExcelUtil.getReader(fileExcel);
            List<List<Object>> readAll = reader.read();
            Boolean flag = ExcelImportUtils.importExcel(readAll);
            if (!flag) {
                return Result.error("数据解析过程中出现异常！");
            }
            return Result.success();
        } finally {
            //在方法结束时删除临时文件，防止导致磁盘空间占用问题。
            fileExcel.delete();
        }
    }

    @PostMapping("/export")
    public Result exportExcel(HttpServletResponse response) throws IOException {
        List<User> userList=userService.exportExcelUser();
//        使用生成文件的方式导出数据
        String sheetName="用户信息";
        String uuid= UUID.randomUUID().toString().replace("-","");
        String timeId= LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss"));
        String fileName=timeId+"-"+uuid+".xlsx";
        Path exportPath= Paths.get("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\"+fileName);
//        File file=new File("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\"+timeId+"-"+uuid+".xlsx");
        OutputStream outputStream= Files.newOutputStream(exportPath);
        EasyExcel.write(outputStream,User.class)
                .autoCloseStream(false).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).sheet(sheetName).doWrite(userList);
        log.info("导出的excel文件地址{}",exportPath);
        return Result.success();
    }

    //    /    将查到的数据以文件流的形式导出成excel
    @PostMapping("/exportStream")
    public void exportExcelStream(HttpServletResponse response) throws IOException {
        List<User> userList = userService.exportExcelUser();

        String fileName = "export123.xlsx";
        String sheetName = "用户信息";

        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());

        EasyExcel.write(response.getOutputStream(), User.class)
                .autoCloseStream(false)
                .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())
                .sheet(sheetName)
                .doWrite(userList);
    }
    @DeleteMapping("/deleteFile")
    public void deleteFile(@RequestParam String url){
        aliOssUtil.deleteFile(url);
    }
    @PostMapping("/test")
    public void test(@RequestBody MultipartFile file){
        System.out.println("上传的文件"+file);
}

}